package com.it.travel.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.it.travel.common.ConstEnum;
import com.it.travel.dao.*;
import com.it.travel.dto.admin.AdminProductDTO;
import com.it.travel.pojo.*;
import com.it.travel.service.admin.AdminProductService;
import com.it.travel.vo.Params.PageParams;
import com.it.travel.vo.Params.admin.AdminProductDeatilUpdateParams;
import com.it.travel.vo.Params.admin.AdminProductDetailParams;
import com.it.travel.vo.Params.admin.AdminProductParams;
import com.it.travel.vo.Params.admin.AdminProductSkuUpdateParams;
import com.it.travel.vo.Result;
import com.it.travel.vo.admin.AdminProductCateAddVO;
import com.it.travel.vo.admin.AdminProductDetailVO;
import com.it.travel.vo.admin.AdminProductVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.awt.font.TransformAttribute;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AdminProductServiceImpl implements AdminProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ProductSkuMapper productSkuMapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Resource
    private ProductDetailMapper productDetailMapper;

//    @Resource
//    private

    @Override
    public Result<?> getInfoPage(PageParams pageParams) {
        Integer total = 0;
        HashMap<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<Product> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(pageParams.getKeywords())) { // 关键字不为空才进行模糊查询
            wrapper.like(Product::getName, pageParams.getKeywords());
            total = productMapper.selectCount(wrapper);
        } else {
            total = productMapper.selectCount(null);
        }
        pageParams.setIndex((pageParams.getIndex() - 1) * pageParams.getSize());
        List<AdminProductDTO> adminProductDTOList = productMapper.selectAdminProductPage(pageParams.getIndex(), pageParams.getSize(), pageParams.getKeywords());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<AdminProductVO> list = new ArrayList<>();
        for (AdminProductDTO adminProductDTO : adminProductDTOList) {
            AdminProductVO adminProductVO = new AdminProductVO();
            String description = adminProductDTO.getDescription();
            BeanUtil.copyProperties(adminProductDTO, adminProductVO);
            String format = simpleDateFormat.format(new Date(adminProductDTO.getCreateTime()));
            String shortDescription = description;
            if (description.length() >= 12) {
                shortDescription = description.substring(0, 12) + "......";  // 简短

            }
            adminProductVO.setDescription(shortDescription);
            adminProductVO.setFormatTime(format);

            list.add(adminProductVO);
        }
        List<AdminProductCateAddVO> categoryTree = getCategoryTree();
//        categoryTree.forEach(System.out::println);
//        System.out.println("list = " + list);
        map.put("total", total);
        map.put("productList", list);
        map.put("categoryTree", categoryTree);
        return Result.success(map, "获取数据成功");
    }

    @Override
    @Transactional
    public Result<?> save(AdminProductParams adminProductParams) {
        if (adminProductParams.getCategoryIds() == null) {
//            throw new Exception(); // 抛出异常回滚
            return Result.error(null, "分类没选择，请重试");
        }
        ProductSku productSku = new ProductSku();
        BeanUtil.copyProperties(adminProductParams, productSku);
        productSku.setImg(adminProductParams.getSkuImg());// 名称不一致
        productSku.setCreateTime(System.currentTimeMillis());
        productSku.setUpdateTime(System.currentTimeMillis());
        productSku.setOriginalPrice(adminProductParams.getOrginalPrice());
        productSku.setIsDeleted(0);
        productSku.setSellPrice(adminProductParams.getOrginalPrice() * adminProductParams.getDiscounts());//
        Product product = new Product();
        product.setCreateTime(System.currentTimeMillis());
        product.setUpdateTime(System.currentTimeMillis());
        product.setSoldNum(0);
        product.setName(adminProductParams.getName());
        product.setIsDeleted(0);
//        ProductDetail productDetail = new ProductDetail();
//        productDetail.setCreateTime(System.currentTimeMillis());
//        productDetail.setUpdateTime(System.currentTimeMillis());
//        productDetail.setDescription(adminProductParams.getDescription());
        int insert = productMapper.insert(product);// 产品
//        productDetail.setProductId(product.getId()); // 为关联表设置产品id
//        productDetailMapper.insert(productDetail);  // detail 关联表维护
        if (insert <= 0) {
            return Result.error(null, "新增失败");
        }
        Integer id = product.getId();
        productSku.setProductId(id);  // 进行关联插入
        int insert1 = productSkuMapper.insert(productSku); // sku 关联表维护
        if (insert1 <= 0) {
            return Result.error(null, "新增失败");

        }

        for (Integer categoryId : adminProductParams.getCategoryIds()) { // 取出前台传的分类id进行遍历，维护中间表
            CategoryProduct categoryProduct = new CategoryProduct();
            categoryProduct.setProductId(id);// 产品id
            categoryProduct.setCategoryId(categoryId);
            categoryProduct.setIsDeleted(0);
            int i = categoryProductMapper.insert(categoryProduct);  // 分类产品表的维护
            if (i <= 0) {
                return Result.error(null, "新增失败");
            }
        }
        return Result.success(null, "新增成功");
    }

    @Transactional
    @Override
    public Result<?> delete(Integer id) {
        int i = categoryProductMapper.delete(new QueryWrapper<CategoryProduct>().eq("product_id", id));// 分类商品中间表
        int i1 = productSkuMapper.delete(new QueryWrapper<ProductSku>().eq("product_id", id)); // 商品sku表
        int i2 = productMapper.deleteById(id); // 商品表
        int i3 = productDetailMapper.delete(new QueryWrapper<ProductDetail>().eq("product_id", id));// 商品细节表
        if (i > 0 && i1 > 0 && i2 > 0 && i3 > 0) {
            return Result.success(null, "删除成功");
        }
//        categoryProductMapper.d
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
        return Result.error(null, "删除失败");
    }

    @Override
    @Transactional
    public Result<?> update(AdminProductSkuUpdateParams adminProductSkuUpdateParams) {
        ProductSku productSku = new ProductSku();

        Product product = new Product();
        product.setName(adminProductSkuUpdateParams.getName());
        product.setId(adminProductSkuUpdateParams.getId());
        product.setUpdateTime(System.currentTimeMillis());
        BeanUtil.copyProperties(adminProductSkuUpdateParams, productSku);
        productSku.setProductId(adminProductSkuUpdateParams.getId());
        productSku.setUpdateTime(System.currentTimeMillis());
        productSku.setIsDeleted(0);
        System.out.println("product = " + product);
        int i1 = productMapper.updateById(product);
        System.out.println("productSku = " + productSku);
        int i = productSkuMapper.update(productSku, new QueryWrapper<ProductSku>().eq("product_id", adminProductSkuUpdateParams.getId()));
//         先对中间表进行删除操作
        categoryProductMapper.delete(new QueryWrapper<CategoryProduct>().eq("product_id", adminProductSkuUpdateParams.getId()));
//        再对中间表进行新增操作
        List<Integer> categoryId = adminProductSkuUpdateParams.getCategoryId();
        for (Integer integer : categoryId) {
            CategoryProduct categoryProduct = new CategoryProduct();
            categoryProduct.setProductId(adminProductSkuUpdateParams.getId());
            categoryProduct.setCategoryId(integer);
            categoryProduct.setIsDeleted(ConstEnum.IS_NOTDELETED.getNum());
            categoryProductMapper.insert(categoryProduct);
        }
        if (i > 0 && i1 > 0) {
            return Result.success(null, "修改成功");
        }
        return Result.error(null, "修改失败");
    }

    @Override
    public Result<?> deletebatch(List<Integer> ids) { // 产品详情也要删除
        int count = 0;
        for (Integer id : ids) {
            int i = categoryProductMapper.delete(new QueryWrapper<CategoryProduct>().eq("product_id", id));// 分类商品中间表
            int i1 = productSkuMapper.delete(new QueryWrapper<ProductSku>().eq("product_id", id));// 商品sku表
            int i2 = productMapper.deleteById(id);// 商品表
            int i3 = productDetailMapper.delete(new QueryWrapper<ProductDetail>().eq("product_id", id));// 商品细节表
            count++;
            if (i > 0 && i1 > 0 && i2 > 0 && i3 > 0 && count == ids.size()) {
                return Result.success(null, "删除成功");
            }
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
        return Result.error(null, "删除失败");
    }

    @Override
    @Transactional
    public Result<?> saveProductDetail(AdminProductDetailParams adminProductDetailParams) { // 商品细节新增
        Integer id = adminProductDetailParams.getId();
        ProductDetail productDetail = productDetailMapper.selectOne(new QueryWrapper<ProductDetail>().eq("product_id", id));
        if (productDetail != null) {
            return Result.error(null, "已经新增过了！");
        }
        Product product = new Product();
        ProductDetail productDetail1 = new ProductDetail();
        product.setContent(adminProductDetailParams.getContent());
        product.setId(adminProductDetailParams.getId());
        int i = productMapper.updateById(product);
        productDetail1.setCreateTime(System.currentTimeMillis());
        productDetail1.setUpdateTime(System.currentTimeMillis());
        productDetail1.setDescription(adminProductDetailParams.getDescription());
        productDetail1.setProductId(adminProductDetailParams.getId());
        int insert = productDetailMapper.insert(productDetail1);
        if (i > 0 && insert > 0) {
            return Result.success(null, "新增成功");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
        return Result.error(null, "新增失败");
    }

    @Override
    public Result<?> findProductDetail(Integer id) {
        ProductDetail productDetail = productDetailMapper.selectOne(new QueryWrapper<ProductDetail>().eq("product_id", id));
        Product product = productMapper.selectById(id);
        AdminProductDetailVO adminProductDetailVO = new AdminProductDetailVO();
        adminProductDetailVO.setDescription(productDetail.getDescription());
        adminProductDetailVO.setContent(product.getContent());
        return Result.success(adminProductDetailVO, "获取数据成功");
    }

    @Override
    @Transactional
    public Result<?> updateProductDetail(AdminProductDeatilUpdateParams adminProductDeatilUpdateParams) {
        Product product = new Product();
        product.setId(adminProductDeatilUpdateParams.getId());
        product.setContent(adminProductDeatilUpdateParams.getContent());
        product.setUpdateTime(System.currentTimeMillis());
        ProductDetail productDetail = new ProductDetail();
        productDetail.setDescription(adminProductDeatilUpdateParams.getDescription());
        productDetail.setUpdateTime(System.currentTimeMillis());
        int i1 = productDetailMapper.update(productDetail, new QueryWrapper<ProductDetail>().eq("product_id", adminProductDeatilUpdateParams.getId()));
        int i = productMapper.updateById(product);
        if (i1 > 0 && i > 0) {
            return Result.success(null, "修改成功");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
        return Result.error(null, "修改失败");
    }

    @Override
    public Result<?> getCategoryIds(Integer id) {
//        System.out.println("id = " + id);
        LambdaQueryWrapper<CategoryProduct> wrapper = Wrappers.lambdaQuery();
        wrapper.select(CategoryProduct::getCategoryId);
        wrapper.eq(CategoryProduct::getProductId, id);
        List<CategoryProduct> list = categoryProductMapper.selectList(wrapper);
        List<Integer> integetList = new ArrayList<>();
        for (CategoryProduct categoryProduct : list) {
            integetList.add(categoryProduct.getCategoryId());
        }

        return Result.success(integetList, "yes");
    }


//    private List<AdminProductCateAddVO> getCategoryInfo() {
//        List<Category> categoryList = categoryMapper.selectList(null);
//        List<Category> list = getCategory(categoryList, 0);
//        ArrayList<Category> arrayList = new ArrayList<>();
//        for (Category category : list) {  // 筛选出一级分类
//            if (category.getParentId().equals(0)) {
//                arrayList.add(category);
//            }
//        }
//        ArrayList<AdminProductCateAddVO> list1 = new ArrayList<>();
//        for (Category category : arrayList) { // 转换
//            AdminProductCateAddVO adminProductCateAddVO = new AdminProductCateAddVO();
//            BeanUtil.copyProperties(category, adminProductCateAddVO);
//            list1.add(adminProductCateAddVO);
//        }
//        return list1;
//    }

    private List<Category> recursionCategory(List<Category> categoryList, Integer pid) {
        List<Category> list = new ArrayList<>();
        for (Category category : categoryList) {
            if (0 == pid) {  // 一级分类
                list.add(category);
                Integer id = category.getId();
                List<Category> category1 = recursionCategory(categoryList, id);
                category.setChildren(category1);
            } else if (pid.equals(category.getParentId())) {
                list.add(category);
                Integer id = category.getId();
                List<Category> category1 = recursionCategory(categoryList, id);
                category.setChildren(category1);
            }
        }
        return list;
    }

    private List<AdminProductCateAddVO> getCategoryTree() {
        List<Category> categoryAll = categoryMapper.selectList(null);
        List<Category> categoryList = recursionCategory(categoryAll, 0);  // 获取树形数据
        List<Category> list = new ArrayList<>();
        for (Category category1 : categoryList) {
            if (category1.getParentId() == 0) {  // 获取一级分类的数据
                list.add(category1);
            }
        }
        List<AdminProductCateAddVO> list1 = new ArrayList<>();
        for (Category category : list) { // 进行对象的转换
            AdminProductCateAddVO adminProductCateAddVO = new AdminProductCateAddVO();
            adminProductCateAddVO.setChildren(category.getChildren());
            adminProductCateAddVO.setName(category.getName());
            adminProductCateAddVO.setId(category.getId());
            adminProductCateAddVO.setParentId(category.getParentId());
            list1.add(adminProductCateAddVO);
        }
        return list1;
    }


}
